/*
 * CS 567 GUI - Semester Project - "DecisionLists"
 * Jason Frank
 * Spring 2011
 *
 * This File:  Creates the center region (rectangle) that goes in the Butterfly view.
 *
 */

package Decision_Lists;

import java.awt.Color;
import java.awt.Dimension;
//import java.awt.FlowLayout;
import java.awt.Font;
//import java.awt.Graphics2D;
//import java.awt.RenderingHints;
import java.util.TreeMap;
import javax.swing.BorderFactory;
import javax.swing.Box;
import javax.swing.JLabel;
import javax.swing.JLayeredPane;
import javax.swing.JPanel;
import javax.swing.border.EtchedBorder;

/*
 */
public class Butterfly_Center extends JPanel {

  //////////////////////////////////////////
  ///// Class Vars /////////////////////////
  protected DL_Model model;
  protected int panelWidthPref;  // constructor sets these
  protected int panelHeightPref;
  protected final int PAD_FOR_RD_RECT_BTM = 9; // Add some extra space at btm of this panel so it doesn't cut
                                               //  off the bottom of the rounded rect

  protected int summary_width;  // also set in consructor
  protected final int SUMMARY_SIDE_PAD = 65; // for each side
  protected Color panel_BG_color = new Color(255,255,255); // white
  protected Color parent_BG_color;  // The color that should appear on the OUTSIDE THE ROUNDED CORNERS
                                    //  (to blend in with the bg of this panel)

  protected TreeMap <String, List_Item_Data> items; // ptr for model's map of items

  // Items to layout on this panel:
  protected RoundedRect_Panel bgPanel;
  protected JLabel name_label, name_title, price_label, price_title, summary_label, summary_title;
  protected JPanel resizedPicPanel;  // the main pic (attached to a Jpanel), after being resized to fit

  protected Font name_label_font = new    Font("Helvetica", Font.BOLD,  19);
  protected Font name_title_font = new    Font("Helvetica", Font.PLAIN, 19);
  protected Font price_label_font = new   Font("Helvetica", Font.PLAIN,  16);
  protected Font price_title_font = new   Font("Helvetica", Font.PLAIN, 16);
  protected Font summary_label_font = new Font("Helvetica", Font.PLAIN,  12);
  protected Font summary_title_font = new Font("Helvetica", Font.PLAIN, 15);
  

  // Layered Pane stuff
  protected int layered_level = 0;  // to start with (for underlying rounded rectangle)
  protected JLayeredPane layeredPane = new JLayeredPane();
  // Main Pic and it's border sizing/spacing
  protected  final int BORDER_OFFSET   = 3;   // # pixels desired from border (right & bottom sides at least)
                                           // Scaling the image to this # of pixels less than the image's Jpanel
                                           //  makes the pic have a few pixel gap before it runs into the border.
  protected final int MAIN_PIC_WIDTH  = 170;
  protected final int MAIN_PIC_HEIGHT = 140 - (BORDER_OFFSET / 3);  // subtract some to make border spacing better.

  ///// end Class Vars ////////////////////////////////////////////////////
  /////////////////////////////////////////////////////////////////////////
  

  // Constructor #1
  public Butterfly_Center(DL_Model model, int width, int height, Color parent_bg)  {

    this.model = model;           // link the model to this view
    this.panelWidthPref  = width;
    this.panelHeightPref = height;
    this.parent_BG_color = parent_bg;
    this.summary_width = panelWidthPref - (SUMMARY_SIDE_PAD * 2); // allow padding on left and right
    setBackground(parent_bg);  // the color that should appear on the outside of the rounded corners
    
    items = model.getItemsMap();

          // TODO: temp - shows this panel's edge
          //setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

    ////  Prepare the Widgets to be layed-out ///
    initWidgetsBasics();
    List_Item_Data item = items.firstEntry().getValue();
    initWidgetVals(item);
    // Now lay everything out
    layout_current_item();

  } ////// end constructor #1 //////


  // Constructor #2 : takes a List_Item_Data, instead of the model.
  public Butterfly_Center(List_Item_Data item, int width, int height, Color parent_bg)  {
        
    this.panelWidthPref  = width;
    this.panelHeightPref = height;
    this.parent_BG_color = parent_bg;
    this.summary_width = panelWidthPref - (SUMMARY_SIDE_PAD * 2); // allow padding on left and right
    setBackground(parent_bg);  // the color that should appear on the outside of the rounded corners

          // TODO: temp - shows this panel's edge
          //setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

    ////  Prepare the Widgets to be layed-out ///
    initWidgetsBasics();
    initWidgetVals(item);
    // Now lay everything out
    layout_current_item();

  } //////// end constructor #2 ///////////



  // Helper for constructor:  Initializes the visible widgets' BASICS (NOT VALUES). Also see initWidgetVals().
  private void initWidgetsBasics() {

    bgPanel = new RoundedRect_Panel(panelWidthPref, panelHeightPref, Color.WHITE, Color.BLACK);
    name_label = new JLabel();
    name_title = new JLabel();
    name_label.setFont(name_label_font);
    name_title.setFont(name_title_font);
    price_label = new JLabel();
    price_title = new JLabel();
    price_label.setFont(price_label_font);
    price_title.setFont(price_title_font);
    summary_label = new JLabel();
    summary_title = new JLabel();
    summary_label.setFont(summary_label_font);
    summary_title.setFont(summary_title_font);
  } ///////////// end initWidgetsBasics() ////////

  // Helper for constructor.  Initializes the visible widgets' VALUES using the data of the current list item.
  private void initWidgetVals(List_Item_Data item) {

    ////////////////////////////////////////////////////////////////////
    ////// INITIALIZE THE WIDGET VALUES with this list item's vals /////
    name_title.setText("Name: ");
    name_label.setText(item.name);
    price_title.setText("$");
    price_label.setText(format_price(item.price));
    summary_title.setText("Summary: ");

    String summary_formatted = String.format("<html><div style=\"width:%dpx;\">%s</div><html>",
                                              summary_width, item.summary);
    summary_label.setText(summary_formatted);

    // Add Main Pic
    JPanel mainPicPanel = item.getMainPicPanel();
    // Set the size of the main pic area to show up here
    mainPicPanel.setSize(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT);
    mainPicPanel.setMaximumSize(new Dimension(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT));

    int maxSideDimension = MAIN_PIC_WIDTH > MAIN_PIC_HEIGHT ? MAIN_PIC_WIDTH : MAIN_PIC_HEIGHT;
    int picSideDimension = maxSideDimension - BORDER_OFFSET;
    ImageResizeToPanel resizedPicturePanel = new ImageResizeToPanel(item.getMainPicBufferedImage(), picSideDimension);
    resizedPicturePanel.setSize(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT);
    resizedPicturePanel.setMaximumSize(new Dimension(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT));
    // Add a pinstripe border around the pic
    resizedPicturePanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

    this.resizedPicPanel = resizedPicturePanel;

  } ////////// end initWidgetVals() ////////

  // <editor-fold defaultstate="collapsed" desc="paintComponent() [not used now]">
  /*
  @Override
  public void paintComponent(Graphics g) {

    //System.out.println("beg of paintComponent in Butterfly_Center()");
    ////// INTITIAL SETUP ////
    // Call the superclass paintComponent() to clear the clipping region (avoids ghosting).
    super.paintComponent(g);
    // make a deep copy of the Graphics object before modifying it
    Graphics myG = g.create();
    Graphics2D g2 = (Graphics2D) myG;
    // Trying to make things ANTI-ALIASED (doens't seem to work though)
    g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    g2.setRenderingHint(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
    // Call the superclass paintComponent() to clear the clipping region (avoids ghosting).
    //    super.paintComponent(g);
    // setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

    ////////////////////////////////////////////////////////////////////
    // Setup the OVERALL UNDERLYING SHAPE (rounded corner rectangle) ///
    g2.setStroke(new BasicStroke(3));

    g2.setColor(Color.white);
    g2.fillRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 25, 25);
    g2.setColor(Color.black);
    g2.drawRoundRect(1, 1, getWidth() - 2, getHeight() - 2, 25, 25);
    // Couldn't get the rounded corners to work with this...
    //    LineBorder roundedBorder = new LineBorder(Color.BLUE, 1, true);
    //    System.out.println("Border will be drawn with rounded corners? " + roundedBorder.getRoundedCorners());
    //    setBorder(roundedBorder);

    myG.setColor(Color.black);

    // myG.drawString("This is Butterfly_Center", 20, 30);

    ///////////////////////////////////////////////////
    ///// Add the CURRENT LIST ITEM to the view. //////
    layout_current_item();



    //System.out.println("near end of paintCompoent in Butterfly_Center()");

    // clear up resources
    myG.dispose();

  } ///// end paintComponent() */ /////  </editor-fold>
 

  
  ///////////////////////////////////////////////////////////////////
  // LAYOUT A LIST ITEM /////////////////////////////////////////////
  //
  // Function also must grab values from the current list item before laying things out
  //
  private void layout_current_item() {
    // TODO: add a parameter to this function to take a particular list item (rather than just grabbing an arbritrary one)
    // Get the first item from the list to start with
//    List_Item_Data item = items.firstEntry().getValue();
//
//    ////////////////////////////////////////////////////////////////////
//    ////// INITIALIZE THE WIDGET VALUES with this list item's vals /////
//    name_title.setText("Name: ");
//    name_label.setText(item.name);
//    price_title.setText("$");
//    price_label.setText(format_price(item.price));
//    summary_title.setText("Summary: ");
//
//    String summary_formatted = String.format("<html><div style=\"width:%dpx;\">%s</div><html>",
//                                              summary_width, item.summary);
//    summary_label.setText(summary_formatted);



        // <editor-fold defaultstate="collapsed" desc="Couldn't get the ROUNDED CORNERS to work with this method...">
          // Couldn't get the rounded corners to work with this method...
          //LineBorder roundedBorder = new LineBorder(Color.BLACK, 1, true);
          //System.out.println("Border will be drawn with rounded corners? " + roundedBorder.getRoundedCorners());
          //setBorder(roundedBorder);// </editor-fold>

    /////////////////////////////////////
    //// LayeredPane setup//////  ///////  http://stackoverflow.com/questions/4280281/making-jbuttons-overlap
    layeredPane.setPreferredSize(this.getPreferredSize());  // take up the whole panel
                //layeredPane.setLayout(new FlowLayout());
                //layeredPane.setLayout(null);
                //layeredPane.add(bgPanel, new Integer(layered_level));

    ////////////////////////////////////////////////////////
    /// First add the UNDERLYING ROUNDED-RECT at a lower level (must set its size/location first)
    bgPanel.setLocation(0, 0);
    bgPanel.setSize(panelWidthPref, panelHeightPref);
    layeredPane.add(bgPanel, layered_level, -1);

    layered_level++; // increment so other widgets get put on top of the rounded rect bg
    ////////////////////////////////////////////////////////////
    // Add everything (except the underlying rounded rect) to the "outerBox", then add it to the layeredPane
    Box outerBox = Box.createVerticalBox();
    // header stuff: "Name: Cabin in Woods"
    Box headerBox = Box.createHorizontalBox();
    headerBox.add(name_title);
    headerBox.add(name_label);

    outerBox.setSize(panelWidthPref, panelHeightPref);
    outerBox.add(Box.createRigidArea(new Dimension(0, 10))); // start vert padding
    outerBox.add(headerBox);
 
//    // Add Main Pic
//    JPanel mainPicPanel = item.getMainPicPanel();
//    // Set the size of the main pic area to show up here
//    mainPicPanel.setSize(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT);
//    mainPicPanel.setMaximumSize(new Dimension(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT));

          // <editor-fold defaultstate="collapsed" desc="Image Scaling via AffineTransform (not used now)">
          // Trying to scale the image to fit these displayed area:
          // (http://stackoverflow.com/questions/4216123/how-to-scale-a-bufferedimage)
            //BufferedImage before = item.getMainPicBufferedImage();
            //int w = before.getWidth();
            //int h = before.getHeight();
            //BufferedImage after = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
            //AffineTransform at = new AffineTransform();
            //at.scale(.3, .3);  // temp scaling vals - just trying to see if this scales it down at all
            //AffineTransformOp scaleOp =
            //new AffineTransformOp(at, AffineTransformOp.TYPE_BILINEAR);
            //after = scaleOp.filter(before, after);// </editor-fold>

//    int maxSideDimension = MAIN_PIC_WIDTH > MAIN_PIC_HEIGHT ? MAIN_PIC_WIDTH : MAIN_PIC_HEIGHT;
//    int picSideDimension = maxSideDimension - BORDER_OFFSET;
//    ImageResizeToPanel resizedPicPanel = new ImageResizeToPanel(item.getMainPicBufferedImage(), picSideDimension);
//    resizedPicPanel.setSize(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT);
//    resizedPicPanel.setMaximumSize(new Dimension(MAIN_PIC_WIDTH, MAIN_PIC_HEIGHT));
//    // Add a pinstripe border around the pic
//    resizedPicPanel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));

    outerBox.add(Box.createRigidArea(new Dimension(0, 15)));  // padding between Name and next stuff below
    // single-entity box just so I can put glue beneath the pic to match the vert look of the price
    Box pic_box = Box.createVerticalBox();
    pic_box.add(resizedPicPanel);
    pic_box.add(Box.createVerticalGlue());

    // box to hold the main pic and the price
    Box pic_price_box = Box.createHorizontalBox();  

            //pic_price_box.add(resizedPicPanel);
    pic_price_box.add(Box.createHorizontalGlue());
    pic_price_box.add(pic_box);
    pic_price_box.add(Box.createHorizontalGlue());

    Box price_box = Box.createHorizontalBox();
    price_box.add(price_title);
    price_box.add(price_label);
    price_box.add(Box.createHorizontalGlue());

    Box price_box_container = Box.createVerticalBox();
    price_box_container.add(price_box);
    price_box_container.add(Box.createVerticalGlue());

    pic_price_box.add(price_box_container);
            // pic_price_box.setBorder(BorderFactory.createEtchedBorder());
    // Put all the pic and price stuff into the main outer box
    outerBox.add(pic_price_box);
    // SUMMARY stuff
    //  First make an outer box to center the summary stuff horizontally, etc
    Box summary_horiz_box = Box.createHorizontalBox();
    summary_horiz_box.add(Box.createRigidArea(new Dimension(15, 0)));  // Summary stuff LEFT side padding
            // summary_horiz_box.add(Box.createRigidArea(new Dimension(SUMMARY_SIDE_PAD, 0)));  // Summary stuff LEFT side padding

    // Add the main summary stuff
    Box summary_elements_box = Box.createVerticalBox();  // holds both "summary:" and the actual sentences part
    Box summary_title_box = Box.createHorizontalBox();   // holds only "summary:" (to make it left aligned)
        // summary_title_box.add(Box.createRigidArea(new Dimension(20, 0)));
    summary_title_box.add(summary_title);
    summary_title_box.add(Box.createHorizontalGlue());  // make the "summary:" part left aligned
    summary_elements_box.add(summary_title_box);
    summary_elements_box.add(Box.createRigidArea(new Dimension(0, 10))); // vert padding under "Summary:"
    summary_elements_box.add(summary_label);
    // Add the summary_elements to the outer summary box
    summary_horiz_box.add(summary_elements_box);

    summary_horiz_box.add(Box.createRigidArea(new Dimension(15, 0)));  // Summary stuff RIGHT side padding
            // summary_horiz_box.add(Box.createRigidArea(new Dimension(SUMMARY_SIDE_PAD, 0)));  // Summary stuff RIGHT side padding
    summary_horiz_box.add(Box.createHorizontalGlue());
    // Finally, add all the summary stuff to the outer box
    outerBox.add(summary_horiz_box);


    outerBox.add(Box.createRigidArea(new Dimension(0, 10))); // end vert padding
    ////////////////////////////////////////////////////////////
    /// Add the MAIN OUTER BOX to the layered pane level ///////
    layeredPane.add(outerBox, layered_level, -1);
    ////////////////////////////////////////////////////////////
    /// Finally, add the ENTIRE LAYERED PANE to this Jpanel ////
    add(layeredPane);
    
        // <editor-fold defaultstate="collapsed" desc="Tried to get the panel resized via a pack() call...">
        // Tried to get the panel resized via a pack() call, but it seems to need to be done after everything
        //  has been intialized (after constructor, etc). So I'd have to figure out a way to do it that way.
          //revalidate();
          //((JFrame)this.getTopLevelAncestor()).pack();
          // ((JFrame)SwingUtilities.getRoot((Component)this)).pack();// </editor-fold>
    
  } //////// end layout_current_item() /////////////



  
  // <editor-fold defaultstate="collapsed" desc="format_price()">
  // Returns a formatted price (with commas) for better readability.
  private String format_price(int price) {

    String price_unformatted = new String(Integer.toString(price));
    String price_formatted = new String();
    int position = 0;
    int unformatted_length = price_unformatted.length();
    ///////////////////////////////////////////////////////////////////////////////
    ////// 3 Cases: either 0,1, or 2 beginning digits before the first comma //////

    // First take the first chunk of digits before transferring all other chunks (3 cases for this)
    switch (price_unformatted.length() % 3) {

      case 0:
        price_formatted += price_unformatted.substring(0, 3); // grab first 3
        position = 3;
        price_unformatted = price_unformatted.substring(position, price_unformatted.length()); // chop off 3
        break;
      case 1:
        price_formatted += price_unformatted.substring(0, 1); // grab first 1
        position = 1;
        price_unformatted = price_unformatted.substring(position, price_unformatted.length()); // chop off 3
        break;
      case 2:
        price_formatted += price_unformatted.substring(0, 2); // grab first 2
        position = 2;
        price_unformatted = price_unformatted.substring(position, price_unformatted.length()); // chop off 3
        break;
      default:
        System.err.println("Bad code in switch statement in format_price()!  Ending prog now.");
        System.exit(-1);
    }

    // For the rest of the string, add commas 3 chars at a time until the whole string has been added
    while (position < unformatted_length) {
      price_formatted += ",";
      price_formatted += price_unformatted.substring(0, 3); // grab 3
      position += 3;
      price_unformatted = price_unformatted.substring(3, price_unformatted.length()); // chop off 3
    }

    return price_formatted;

  } ////// end format_price() ///////////// </editor-fold>



  //@Override
  //public Dimension getMinimumSize()   { return getPreferredSize(); }
  @Override
  public Dimension getMinimumSize()   { return new Dimension(panelWidthPref - 100, panelHeightPref - 100);  }

  @Override
  public Dimension getPreferredSize() { 
    
    return new Dimension(panelWidthPref, panelHeightPref + PAD_FOR_RD_RECT_BTM);
  }
  @Override
  public Dimension getMaximumSize() {   return new Dimension(panelWidthPref + 100, panelHeightPref + 100); }

  //@Override
  //public Dimension getMaximumSize() {   return getPreferredSize(); }
  

} //////////////////// end class Butterfly_Center /////////////////////////////
